﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using Library;
using System.IO;
using System.ServiceModel;
namespace Thi
{
    public partial class FrmGioiThieu : Form
    {
        svDangNhap.LoginClient sv;
        public static string mConnect = "Server=192.168.100.100;database=Exam18;uid=sa;pwd=123456";
        private string msql = "";
        public DGC_Library mLibrary = new DGC_Library(mConnect);
        DataTable dtGhiChu = new DataTable();
        //public DGC_String mString = new DGC_String();

        

        //Bien kiem tra
        static int m_Tab = 0;
        static int m_TabDangTao = 0;
        bool m_TaoXongTab = false;
        bool m_ChuaTaoXongTabmaBamLui = false;
      

        static int m_LoaiDA = 0;
        string ms_lop = "";//"10-12A1";
        string m_Manguoidung = "";//"TEST123";//FrmChonMonThi.Manguoidung;
        string m_Tennguoidung = "";//"Bui quang thai";//FrmChonMonThi.Tennguoidung;
        string m_ms_hssvthi = "";//"32";
        string m_ms_Mondaotao = "";//"16";
        string m_Lanthi = "";//"0";
        int m_thoigianlambai = 0;//1;//phut
        DataTable m_dtThongTinThi = null;
        int m_Diem = 0;
        DataTable m_dtThongTinCauHoi = null;


        //DataTable m_dtGhichuThi = null;
        string m_tenmonthi = "";
        string m_hinhthucthi = "";
        string m_ngaythi = "";

        
        //Hai table luu thong tin
        DataTable tb_hssvthi = null;//chua thong tin ket qua dau rot
        DataTable tb_masodethi = null;//chua ghi chu truoc va sau
        FrmChatClient frmChat;
        public FrmGioiThieu(string m_tenmonthi, string m_hinhthucthi, string m_Tennguoidung, DataTable tb_masodethi, DataTable tb_hssvthi)
        {
            InitializeComponent();
            //this.frmChat = frmChat;
            //this.dtGhiChu = dtGhiChu;
            //Load ghi chu truoc
           // this.LoadNoidung(RichPhandau, (byte[])dtGhiChu.Rows[0]["ghichutruoc"]);


            //lay du lieu 2 table goc 
            this.tb_masodethi = tb_masodethi;//mLibrary.GetDataTable("select * from tb_masodethi where MS_Mondaotao=16", "tb_masodethi");
            this.tb_hssvthi = tb_hssvthi;//mLibrary.GetDataTable("select * from dbo.tb_hssvthi where MS_hssvthi=34 " +
                                             //   " and MS_Lop='10-12A1' and MS_hssv='TEST123' "+
                                              //  " and MS_Mondaotao=16 and  MS_loaithi=2", "tb_hssvthi");
            //Get thong tin tu 2 table
            this.GetThongTin(m_tenmonthi, m_hinhthucthi, m_Tennguoidung, tb_hssvthi, tb_masodethi);            
           
            //trang thai control
            panelTruoc.Visible = true;
            panelSau.Visible = false;
            tabCauhoi.Visible = false;
            
        }
        private void GetThongTin(string m_tenmonthi, string m_hinhthucthi, string m_Tennguoidung, DataTable tb_hssvthi, DataTable tb_masodethi)
        {
            //m_dtGhichuThi = mLibrary.GetDataTable(" Select * from tb_masodethi where ms_Mondaotao=16", "123");
            this.m_tenmonthi = m_tenmonthi;// "Môn tổng hợp";//tb_masodethi.Rows[0][""].ToString();
            this.m_hinhthucthi = m_hinhthucthi;// "Thi học kỳ I";
            m_ngaythi = tb_hssvthi.Rows[0]["ngaythi"].ToString();//"02/12/2010";
            ms_lop = tb_hssvthi.Rows[0]["ms_lop"].ToString();//"10-12A1";
            m_Manguoidung = tb_hssvthi.Rows[0]["ms_hssv"].ToString();//"TEST123";//FrmChonMonThi.Manguoidung;
            this.m_Tennguoidung = m_Tennguoidung;//"Bui quang thai";//FrmChonMonThi.Tennguoidung;
            m_ms_hssvthi = tb_hssvthi.Rows[0]["ms_hssvthi"].ToString();//"32";
            m_ms_Mondaotao = tb_hssvthi.Rows[0]["ms_Mondaotao"].ToString();//"16";
            m_Lanthi = tb_hssvthi.Rows[0]["lanthi"].ToString(); //"0";
            m_thoigianlambai = int.Parse(tb_masodethi.Rows[0]["thoigianlambai"].ToString());//1;//phut
        }




        private void FrmGioiThieu_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }     

      
        private void butCausau_Click(object sender, EventArgs e)
        {
            try
            {              
                m_Tab = m_Tab + 1;
              
                if (!m_TaoXongTab)//khi chua tao xong tab
                {
                    if (m_ChuaTaoXongTabmaBamLui)
                    {
                        if (m_TabDangTao <= m_SoCauHoi)
                        {
                            this.ThucThiGiaoDien(m_TabDangTao);//so tab hien thoi
                            butCauTruoc.Enabled = true;
                            label1.Text = "Câu hiện tại " + m_TabDangTao + " trong " + m_SoCauHoi + " câu hỏi";
                        }
                        if (m_TabDangTao == m_SoCauHoi)
                        {
                            butCausau.Enabled = false;
                            m_TaoXongTab = true;
                        }
                        m_TabDangTao++;
                    }
                    else
                    {
                        m_TabDangTao = m_Tab+1;
                        if (m_Tab <= m_SoCauHoi)
                        {
                            this.ThucThiGiaoDien(m_Tab);//so tab hien thoi
                            butCauTruoc.Enabled = true;
                            label1.Text = "Câu hiện tại " + m_Tab + " trong " + m_SoCauHoi + " câu hỏi";
                        }
                        if (m_Tab == m_SoCauHoi)
                        {
                            butCausau.Enabled = false;
                            m_TaoXongTab = true;
                        }
                    }
                   
                }
                else//khi da tao xong tab,quay lai cau hoi
                {
                    foreach (TabPage ctrl in tabCauhoi.Controls)
                    {
                        if (ctrl.Name == "tab" + m_Tab)
                        {
                            tabCauhoi.SelectedTab = ctrl;
                        }
                    }            
                }
            }
           catch (Exception)
            {
                txtthongbao1.Text = "Kết nối tới sever không thành công";
                txtthongbao1.ForeColor = Color.Red;
            }
        }     
        private void butBatDau_Click(object sender, EventArgs e)
        {
            try
            {
                //trang thai control
                panelTruoc.Visible = false;
                panelSau.Visible = false;
                tabCauhoi.Visible = true;



                m_Tab = 1;
                //Thong tin thi:so cau hoi,thoi gian lam bai,diem toi da,ghi chu truoc sau
                //msql = "Select * from tb_masodethi where ms_Mondaotao=" + m_ms_Mondaotao;
                m_dtThongTinThi = tb_masodethi;//mLibrary.GetDataTable(msql, "123");
                //Diem thi
                //msql = "Select case when diem is null then 0 Else diem End as diem " +
                //       "from( Select  min(diem)as diem from tb_capdokhoCT a inner join tb_capdokho b " +
                //       "on a.MS_capdo=b.ms_capdo inner join tb_Cauhinhcapdo c on b.MS_capdo=c.ms_capdo " +
                //       "where c.ms_mondaotao=16 ) as A";
                //m_Diem = mLibrary.Timso_int(msql);
                //Thong tin thi giua chung tat dot ngot
                //msql = "Select * from tb_HSSVthiCT where ms_hssvthi=" + m_ms_hssvthi + " and Lanthi="+m_Lanthi;
                //m_dtThongTinCauHoi = mLibrary.GetDataTable(msql, "table");
                ///////////Thuc thi tren giao dien/////////
                //Tao Tab cau hoi////
                m_SoCauHoi = int.Parse(m_dtThongTinThi.Rows[0]["Soluongcauhoi"].ToString());
                this.ThucThiGiaoDien(1);//so tab hien thoi

                //nut an
                m_Tab = 1;
                butBatDau.Enabled = false;
                butCausau.Enabled = true;
                butXemlai.Enabled = true;
                butKetthuc.Enabled = true;
                label1.Text = "Câu hiện tại " + m_Tab + " trong " + m_SoCauHoi + " câu hỏi";
                this.ShowTime();

                label1.Visible = label2.Visible = true;
                tThuBai.Start();
            }
            catch (Exception ex)
            {
                txtthongbao1.Text = "Kết nối tới sever không thành công";
                txtthongbao1.ForeColor = Color.Red;
            }
        }
        int m_SoCauHoi=0;
        private void ThucThiGiaoDien(int i)
        {
            //for (int i = 1; i <= mSoCauHoi; i++)
            //{
                TabPage Tabpage = new TabPage();
                tabCauhoi.Controls.Add(Tabpage);
                Tabpage.Name = "tab" + i;
                Tabpage.TabIndex = i;
                Tabpage.Text = "Câu " + i;
                Tabpage.UseVisualStyleBackColor = true;
                
                //tab hien thi
                tabCauhoi.SelectedTab = Tabpage;

                
                //Thêm option "Danh dau da chon"
                CheckBox checkbox = new CheckBox();
                Tabpage.Controls.Add(checkbox);
                checkbox.AutoSize = true;
                checkbox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                checkbox.ForeColor = System.Drawing.Color.Red;
                checkbox.Location = new System.Drawing.Point(21, 4);
                checkbox.Name = "check" + i;
                checkbox.Size = new System.Drawing.Size(151, 20);
                checkbox.TabIndex = 0;
                checkbox.Text = "Đánh dấu đã chọn";
                checkbox.UseVisualStyleBackColor = true;
                checkbox.CheckedChanged += new EventHandler(checkbox_CheckedChanged);
                //label
                Label labgt = new Label();
                Tabpage.Controls.Add(labgt);
                labgt.AutoSize = true;
                labgt.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                labgt.ForeColor = System.Drawing.Color.Red;
                labgt.Location = new System.Drawing.Point(22, 86);
                labgt.Name = "labgt" + i;
                labgt.Size = new System.Drawing.Size(292, 16);
                labgt.TabIndex = 0;
                labgt.Text = "Các phương án chọn (1 hay nhiều đáp án)";

                ////////////////Thêm dap an cau tra loi
                //Lay thong tin cau hoi
                DataTable dtThongTinCauHoi = this.LayThongTinCauHoi(m_ms_hssvthi, ms_lop, i);

                if (dtThongTinCauHoi.Rows.Count > 0)
                {
                    //Them noi dung cau hoi                      
                    RichTextBox noidung = new RichTextBox();
                    Tabpage.Controls.Add(noidung);
                    noidung.Location = new System.Drawing.Point(21, 25);
                    noidung.Name = "NDCH" + i;
                    noidung.ReadOnly = true;
                    noidung.Size = new System.Drawing.Size(965, 57);
                    noidung.TabIndex = i;
                    //noidung.Text = "";
                    this.LoadNoidung(noidung, (byte[])(byte[])dtThongTinCauHoi.Rows[0]["noidung"]);

                    //noi dung
                    //Loai cau hoi:1 dap an (0),nhieu dap an (1)
                    int poin = 76;//khoang cach giua cac cau tra loi (vi tri Check hay radio)

                    if (dtThongTinCauHoi.Rows[0]["TTcauhoi"].ToString() == "1")//nhieu dap an
                    {
                        for (int k = 1; k < dtThongTinCauHoi.Rows.Count; k++)
                        {
                            //checkbox
                            int kc = poin * k;
                            CheckBox checkCH = new CheckBox();
                            Tabpage.Controls.Add(checkCH);
                            checkCH.AutoSize = true;
                            checkCH.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                            checkCH.Location = new System.Drawing.Point(21, 32 + kc);
                            checkCH.Name = "CHcheck" + k;
                            checkCH.TabIndex = k;
                            //checkCH.Text = "checkCH";
                            checkCH.UseVisualStyleBackColor = true;
                    
                            //noidung
                            RichTextBox noidungcheck = new RichTextBox();
                            Tabpage.Controls.Add(noidungcheck);
                            noidungcheck.Location = new System.Drawing.Point(39, 33 + kc);
                            noidungcheck.Name = "noidungcheck" + k;
                            noidungcheck.ReadOnly = true;
                            noidungcheck.TabIndex = k;
                            noidungcheck.Size = new System.Drawing.Size(947, 69);
                            //noidungradio.Text = "";
                            this.LoadNoidung(noidungcheck, (byte[])(byte[])dtThongTinCauHoi.Rows[k]["noidung"]);
                        }
                    }
                    else
                    {
                        for (int k = 1; k < dtThongTinCauHoi.Rows.Count; k++)
                        {
                            //radio
                            int kc = poin * k;
                            RadioButton radioCH = new RadioButton();
                            Tabpage.Controls.Add(radioCH);
                            radioCH.AutoSize = true;
                            radioCH.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                            radioCH.Location = new System.Drawing.Point(21, 32 + kc);
                            radioCH.Name = "CHradio" + k;
                            radioCH.Size = new System.Drawing.Size(113, 20);
                            radioCH.TabIndex = k;
                            radioCH.TabStop = true;
                            //radioCH.Text = "radioCH"+k;
                            radioCH.UseVisualStyleBackColor = true;
                        
                            //noidung
                            RichTextBox noidungradio = new RichTextBox();
                            Tabpage.Controls.Add(noidungradio);
                            noidungradio.Location = new System.Drawing.Point(39, 33 + kc);
                            noidungradio.Name = "noidungradio" + k;
                            noidungradio.ReadOnly = true;
                            noidungradio.TabIndex = k;
                            noidungradio.Size = new System.Drawing.Size(947, 69);
                            //noidungradio.Text = "";
                            this.LoadNoidung(noidungradio, (byte[])(byte[])dtThongTinCauHoi.Rows[k]["noidung"]);
                        }
                    }
                }
            //}
        }


        private DataTable LayThongTinCauHoi(string ms_hssvthi, string ms_lop, int thutu)
        {
            //msql = "Select a.* from tb_Nganhangdethi a inner join tb_cauhinhlop b on (a.ms_Mondaotao=b.ms_Mondaotao) " +
            //              " inner join tb_hssvlop c on (b.ms_lop=c.ms_lop)inner join tb_hssvthi d on " +
            //              " (b.ms_Mondaotao=d.ms_mondaotao) and d.ms_hssv=c.ms_hssv inner join tb_HSSVthiCT e on " +
            //              " (d.MS_hssvthi=e.MS_hssvthi) where a.cauhoi=e.cauhoi and e.MS_hssvthi=" + ms_hssvthi + " and e.cauhoiID=" + thutu +
            //              " and e.lanthi=" + m_Lanthi + " and b.ms_lop='" + ms_lop + "' order by a.cauhoiid";
            //DataTable dtThongTinCauHoi = mLibrary.GetDataTable(msql, "qw");
            DataTable dt = null;
            try
            {
                
                sv = new Thi.svDangNhap.LoginClient();
                dt= sv.LayThongTinCauHoi(FrmChonMonThi.Manguoidung,m_Lanthi, ms_hssvthi, ms_lop, thutu);
                txtthongbao1.Text = "";
            }
            catch (Exception)
            {
                txtthongbao1.Text = "Kết nối tới sever không thành công";
                txtthongbao1.ForeColor = Color.Red;
            }
            finally
            {
                if (sv.State != CommunicationState.Faulted)
                    sv.Close();
            }
            return dt;
        }      

        bool m_KiemTraLuu = false;
        bool m_KiemTraLoaiCH = false;
        string m_CauTraLoi = "";

        private void checkbox_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                //kiemtra xemtab nao dang duoc chon
                foreach (TabPage ctrl in tabCauhoi.Controls)
                {
                    if (ctrl == tabCauhoi.SelectedTab)
                    {
                        //m_Tab = tabCauhoi.SelectedIndex + 1;
                        //Kiem tra co chon Luu ko                        
                        foreach (Control check in ctrl.Controls)
                        {
                            if (check is CheckBox && check.Name == "check" + m_Tab)//la check chon luu
                            {
                                CheckBox a = (CheckBox)check;
                                if (a.Checked)
                                {
                                    string traloi = "";
                                    foreach (Control check_radio in ctrl.Controls)
                                    {
                                        if (check_radio.Name!=check.Name && check_radio is CheckBox || check_radio is RadioButton)
                                        {
                                            CheckBox cb;
                                            RadioButton rb;
                                            if (check_radio is CheckBox)
                                            {
                                                cb = (CheckBox)check_radio;
                                                if (cb.Checked && check_radio.Name.Substring(0, 2) == "CH")
                                                {
                                                    traloi = traloi + check_radio.Name.Substring(check_radio.Name.Length - 1) + ";";
                                                }
                                            }
                                            if (check_radio is RadioButton)
                                            {
                                                rb = (RadioButton)check_radio;
                                                if (rb.Checked && check_radio.Name.Substring(0, 2) == "CH")
                                                {
                                                    traloi = traloi + check_radio.Name.Substring(check_radio.Name.Length - 1) + ";";
                                                }
                                            }
                                        }
                                    }
                                    sv = new Thi.svDangNhap.LoginClient();
                                   sv.CapNhatCauHoiDaChon(FrmChonMonThi.Manguoidung,traloi, m_ms_hssvthi, m_Tab, m_Lanthi);
                                }
                                else
                                {
                                    //Luu cau tra loi truoc neu chua chon
                                    sv = new Thi.svDangNhap.LoginClient();
                                    sv.CapNhatcauHoiNhungChuaChonLuu(FrmChonMonThi.Manguoidung,m_ms_hssvthi, m_Tab, m_Lanthi);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {

                txtthongbao1.Text = "Kết nối tới sever không thành công";
                txtthongbao1.ForeColor = Color.Red;
            }
            finally
            {
                if (sv.State != CommunicationState.Faulted)
                    sv.Close();
            }
        }

      

        private void LoadNoidung(RichTextBox rt,byte[] noidung)
        {           
            Stream theFile = new MemoryStream(noidung);
            rt.LoadFile(theFile, RichTextBoxStreamType.RichText);
        }
       

        private void tabCauhoi_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //kiemtra xemtab nao dang duoc chon
                foreach (TabPage ctrl in tabCauhoi.Controls)
                {
                    if (ctrl == tabCauhoi.SelectedTab)
                    {
                        m_Tab = tabCauhoi.SelectedIndex + 1;                            
                    }
                }     
                //
              
            }
            catch (Exception ex)
            {
                txtthongbao1.Text = "Kết nối tới sever không thành công";
                txtthongbao1.ForeColor = Color.Red;
            }
        }


        int seconds=0; // Seconds.
        int minutes=0; // Minutes.
        int hours=0;   // Hours.

        private void timer1_Tick(object sender, EventArgs e)
        {           
            if ((minutes == 0) && (hours == 0) && (seconds == 0))
            {         
                timer1.Enabled = false;
                MessageBox.Show("Hết thời gian làm bài Thi, Bấm OK để xem kết quả","Thông báo",MessageBoxButtons.OK,MessageBoxIcon.Stop);
                this.Xemketqua();    
            }
            else
            {             
                if (seconds < 1)
                {
                    seconds = 59;
                    if (minutes == 0)
                    {
                        minutes = 59;
                        if (hours != 0)
                            hours -= 1;
                    }
                    else
                    {
                        minutes -= 1;
                    }
                }
                else
                    seconds -= 1;
            

                string h,p,s;
                if(hours.ToString().Length!=2) h= "0"+hours.ToString(); else h= hours.ToString();
                if(minutes.ToString().Length!=2) p= "0"+minutes.ToString(); else p= minutes.ToString();
                if(seconds.ToString().Length!=2) s= "0"+seconds.ToString(); else s= seconds.ToString();
                label2.Text = "Thời gian làm bài: " + h + ":" + p + ":" + s;
           }
        }


       
        private void ShowTime()
        {
             hours =m_thoigianlambai/60;
             seconds = 0;
             minutes =  m_thoigianlambai%60;
             timer1.Start();
        }

        private void butXemlai_Click(object sender, EventArgs e)
        {
            try
            {
                //Kiem tra control
                DataTable dt = new DataTable();
                DataColumn auto = new DataColumn("Value", typeof(System.String));
                dt.Columns.Add(auto);
                //
                string value = "";
                foreach (TabPage ctrl in tabCauhoi.Controls)
                {
                    value = ctrl.Text;
                    foreach (Control check in ctrl.Controls)
                    {
                        if (check is CheckBox && check.Name.Substring(0,5) == "check")//la check chon luu
                        {
                            CheckBox a = (CheckBox)check;
                            if (a.Checked)
                            {
                                value = value + "    " + "Đã chọn  " + "         ";
                            }
                            else
                            {
                                value = value + "    " + "Chưa chọn" + "         ";
                            }

                            foreach (Control check_radio in ctrl.Controls)
                            {
                                if (check_radio.Name != check.Name && check_radio is CheckBox || check_radio is RadioButton)
                                {
                                    CheckBox cb;
                                    RadioButton rb;
                                    if (check_radio is CheckBox)
                                    {
                                        cb = (CheckBox)check_radio;
                                        if (cb.Checked && check_radio.Name.Substring(0, 2) == "CH")
                                        {
                                            value = value + check_radio.Name.Substring(check_radio.Name.Length - 1) + ";";
                                        }
                                    }
                                    if (check_radio is RadioButton)
                                    {
                                        rb = (RadioButton)check_radio;
                                        if (rb.Checked && check_radio.Name.Substring(0, 2) == "CH")
                                        {
                                            value = value + check_radio.Name.Substring(check_radio.Name.Length - 1) + ";";
                                        }
                                    }
                                }
                            }
                        } 
                        break;
                    }
                  


                    //them vao datatable
                    DataRow row = null;
                    row = dt.NewRow();
                    row["Value"] = value.Substring(0,value.Length-1);                   
                    dt.Rows.Add(row);
                }
                FrmXemLai f = new FrmXemLai(dt);
                f.ShowDialog();
            }
            catch (Exception)
            {
                txtthongbao1.Text = "Kết nối tới sever không thành công";
                txtthongbao1.ForeColor = Color.Red;
            }
          
        }

        private void butKetthuc_Click(object sender, EventArgs e)
        {
            DialogResult dl;
            dl = MessageBox.Show("Cẩn thận khi nhấn Kết thúc bài thi \n Hệ thống sẽ tính điểm khi bạn kết thúc \n Nếu muốn quay lại. Bấm No \n Nếu muốn kết thúc bấm Yes", "Thông báo từ hệ thống", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dl == DialogResult.Yes)
            {
                //trang thai control
                panelTruoc.Visible = false;
                panelSau.Visible = true;
                tabCauhoi.Visible = false;
                butXemlai.Enabled = false;
                butKetthuc.Enabled = false;
                butCausau.Enabled = false;

                //
                loaihinhthi.Text = "Loại hình thi : " + m_hinhthucthi;
                ngaythi.Text = "Ngày thi : " + m_ngaythi;
                monthi.Text = "MS môn thi : " + m_tenmonthi;
                lop.Text = "MS Lớp : " + ms_lop;
                mshocvien.Text = "MS Học viên : " + m_Manguoidung;
                tenhocvien.Text = "Tên học viên : " + m_Tennguoidung;
                diemtoida.Text = "Điểm tối đa : " + tb_masodethi.Rows[0]["toida"].ToString();
                this.LoadNoidung(ghichu, (byte[])(byte[])tb_masodethi.Rows[0]["ghichusau"]);

                //Kiem tra xem duoc bao nhieu diem
                DataTable dtDiem=null;
                try
                {
                    sv = new Thi.svDangNhap.LoginClient();
                    // msql = "select * from tb_HSSVthiCT where lanthi="+m_Lanthi+" and ms_hssvthi="+m_ms_hssvthi;
                    dtDiem = sv.KiemTraDiem(FrmChonMonThi.Manguoidung,m_Lanthi, m_ms_hssvthi);//mLibrary.GetDataTable(msql, "Diem");
                    txtthongbao1.Text = "";
                }
                catch (Exception)
                {
                    txtthongbao1.Text = "Kết nối tới sever không thành công";
                    txtthongbao1.ForeColor = Color.Red;
                }
                finally
                {
                    if (sv.State != CommunicationState.Faulted)
                        sv.Close();
                }
               
                
                int Cau = 0;
                for (int i = 0; i < dtDiem.Rows.Count; i++)
                {
                    string dapan = dtDiem.Rows[i]["dapan"].ToString();
                    string traloi = dtDiem.Rows[i]["traloi"].ToString();
                    if (dapan == traloi)
                        Cau++;
                }
                int diemthiTC = 0;
                diemthiTC = (int.Parse(tb_masodethi.Rows[0]["toida"].ToString()) * Cau) / int.Parse(tb_masodethi.Rows[0]["soluongcauhoi"].ToString());
                diemthi.Text="Điểm thi : "+diemthiTC;

                int ketquathi = 0;
                if (diemthiTC >= int.Parse(tb_masodethi.Rows[0]["diemdat"].ToString()))
                {
                    ketqua.Text = "Kết quả : Đạt";
                    ketquathi = 1;
                }
                else
                {
                    ketqua.Text = "Kết quả : Hỏng";

                }
                try
                {
                    //Update thong tin da thi roi
                    //msql = " Update tb_hssvthi set Diemthi =900 ,Ketqua="+ketquathi+" where ms_hssv='"+m_ms_hssvthi+"' and ms_Mondaotao='"+m_ms_Mondaotao+"' "+
                    //       " and Lanthi="+m_Lanthi+" and Ms_loaithi=3";
                    //mLibrary.RunProc(msql);
                    sv = new Thi.svDangNhap.LoginClient();
                    sv.CapNhatThongTinThi(FrmChonMonThi.Manguoidung,diemthiTC, ketquathi, m_ms_hssvthi, m_ms_Mondaotao, m_Lanthi,tb_hssvthi.Rows[0]["ms_loaithi"].ToString());
                    txtthongbao1.Text = "";
                }
                catch (Exception)
                {
                    txtthongbao1.Text = "Kết nối tới sever không thành công";
                    txtthongbao1.ForeColor = Color.Red;
                }
                finally
                {
                    if (sv.State != CommunicationState.Faulted)
                        sv.Close();
                    label1.Visible = label2.Visible = false;

                }

            }
        }

        private void FrmGioiThieu_Load(object sender, EventArgs e)
        {
            this.Text = "HE THONG QUAN LY THI TRAC NGHIEM [Hoc Vien: " + FrmChonMonThi.Manguoidung + "]";
            this.LoadNoidung(truockhithi, (byte[])(byte[])tb_masodethi.Rows[0]["ghichutruoc"]);
        }

        void Xemketqua()
        {
            //trang thai control
            panelTruoc.Visible = false;
            panelSau.Visible = true;
            tabCauhoi.Visible = false;
            butXemlai.Enabled = false;
            butKetthuc.Enabled = false;
            butCausau.Enabled = false;


            loaihinhthi.Text = "Loại hình thi : " + m_hinhthucthi;
            ngaythi.Text = "Ngày thi : " + m_ngaythi;
            monthi.Text = "MS môn thi : " + m_tenmonthi;
            lop.Text = "MS Lớp : " + ms_lop;
            mshocvien.Text = "MS Học viên : " + m_Manguoidung;
            tenhocvien.Text = "Tên học viên : " + m_Tennguoidung;
            diemtoida.Text = "Điểm tối đa : " + tb_masodethi.Rows[0]["toida"].ToString();
            this.LoadNoidung(ghichu, (byte[])(byte[])tb_masodethi.Rows[0]["ghichusau"]);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void tThuBai_Tick(object sender, EventArgs e)
        {
            try
            {
                sv = new Thi.svDangNhap.LoginClient();
                int idtruycap = sv.GetIDTruyCap(m_Manguoidung);
                bool s = sv.KiemTraThuBaiThi(idtruycap.ToString());
                if (s)
                {
                    tThuBai.Stop();
                    MessageBox.Show("Giám thị đã chấm dứt chương trình thi. \n Bấm OK để xem kết quả", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.KetThuc();
                }
            }
            catch (Exception)
            {

            }
            finally
            {
                if (sv.State != CommunicationState.Faulted)
                    sv.Close();
            }           
        }


        private void KetThuc()
        {

            //trang thai control
            panelTruoc.Visible = false;
            panelSau.Visible = true;
            tabCauhoi.Visible = false;
            butXemlai.Enabled = false;
            butKetthuc.Enabled = false;
            butCausau.Enabled = false;

            //
            loaihinhthi.Text = "Loại hình thi : " + m_hinhthucthi;
            ngaythi.Text = "Ngày thi : " + m_ngaythi;
            monthi.Text = "MS môn thi : " + m_tenmonthi;
            lop.Text = "MS Lớp : " + ms_lop;
            mshocvien.Text = "MS Học viên : " + m_Manguoidung;
            tenhocvien.Text = "Tên học viên : " + m_Tennguoidung;
            diemtoida.Text = "Điểm tối đa : " + tb_masodethi.Rows[0]["toida"].ToString();
            this.LoadNoidung(ghichu, (byte[])(byte[])tb_masodethi.Rows[0]["ghichusau"]);

            //Kiem tra xem duoc bao nhieu diem
            DataTable dtDiem = null;
            try
            {
                sv = new Thi.svDangNhap.LoginClient();
                // msql = "select * from tb_HSSVthiCT where lanthi="+m_Lanthi+" and ms_hssvthi="+m_ms_hssvthi;
                dtDiem = sv.KiemTraDiem(FrmChonMonThi.Manguoidung,m_Lanthi, m_ms_hssvthi);//mLibrary.GetDataTable(msql, "Diem");
                txtthongbao1.Text = "";
            }
            catch (Exception)
            {
                txtthongbao1.Text = "Kết nối tới sever không thành công";
                txtthongbao1.ForeColor = Color.Red;
            }
            finally
            {
                if (sv.State != CommunicationState.Faulted)
                    sv.Close();
            }


            int Cau = 0;
            for (int i = 0; i < dtDiem.Rows.Count; i++)
            {
                string dapan = dtDiem.Rows[i]["dapan"].ToString();
                string traloi = dtDiem.Rows[i]["traloi"].ToString();
                if (dapan == traloi)
                    Cau++;
            }
            int diemthiTC = 0;
            diemthiTC = (int.Parse(tb_masodethi.Rows[0]["toida"].ToString()) * Cau) / int.Parse(tb_masodethi.Rows[0]["soluongcauhoi"].ToString());
            diemthi.Text = "Điểm thi : " + diemthiTC;

            int ketquathi = 0;
            if (diemthiTC >= int.Parse(tb_masodethi.Rows[0]["diemdat"].ToString()))
            {
                ketqua.Text = "Kết quả : Đạt";
                ketquathi = 1;
            }
            else
            {
                ketqua.Text = "Kết quả : Hỏng";

            }
            try
            {
                //Update thong tin da thi roi
                //msql = " Update tb_hssvthi set Diemthi =900 ,Ketqua="+ketquathi+" where ms_hssv='"+m_ms_hssvthi+"' and ms_Mondaotao='"+m_ms_Mondaotao+"' "+
                //       " and Lanthi="+m_Lanthi+" and Ms_loaithi=3";
                //mLibrary.RunProc(msql);
                sv = new Thi.svDangNhap.LoginClient();
                sv.CapNhatThongTinThi(FrmChonMonThi.Manguoidung, diemthiTC, ketquathi, m_ms_hssvthi, m_ms_Mondaotao, m_Lanthi, tb_hssvthi.Rows[0]["ms_loaithi"].ToString());
                txtthongbao1.Text = "";
            }
            catch (Exception)
            {
                txtthongbao1.Text = "Kết nối tới sever không thành công";
                txtthongbao1.ForeColor = Color.Red;
            }
            finally
            {
                if (sv.State != CommunicationState.Faulted)
                    sv.Close();
                label1.Visible = label2.Visible = false;

            }
        }
    
    }
}
